//
//  WXPayRequestHandler.m
//  ZLWXPayDemo
//
//  Created by zhangliang on 16/11/24.
//  Copyright © 2016年 zhangliang. All rights reserved.
//

#import "WXPayRequestHandler.h"

@implementation WXPayRequestHandler

//============== 微信支付（包含测试代码）===================
/**
 * 统一下单
 * price 单位为分
 */
+ (void)sendWXPayQueryWithOrderBody:(NSString *)bodyDesc withMoney:(NSString *)price {
    // 应用id
    NSString *appid = kWxAPPID;
    // 商户号 微信支付分配的商户号
    NSString *mch_id = MCH_ID;
    // 随机字符串
    NSString *nonce_str =[WXSignUtil generateTradeNO];
    // 商品描述
    NSString *body = bodyDesc;
    // 商户订单号
    NSString *out_trade_no = [WXSignUtil generateOrderNO];
    // 订单总金额
    NSString *total_fee = price;
    // 接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数
    NSString *notify_url = WX_Notify_URL;
    // 终端ip 用户实际ip
    NSString *spbill_create_ip = [WXSignUtil getClientIP];
    // 交易类型 支付类型这里是APP支付
    NSString *trade_type = @"APP";
    // 交易起始时间
    NSString *time_start = [NSString stringWithFormat:@"%ld", (long)[NSDate date].timeIntervalSince1970];
    
    NSMutableDictionary *originOrderdic = [NSMutableDictionary dictionary];
    [originOrderdic setValue:appid forKey:@"appid"];//公众账号ID
    [originOrderdic setValue:mch_id forKey:@"mch_id"];//商户号
    [originOrderdic setValue:nonce_str forKey:@"nonce_str"];//随机字符串
    [originOrderdic setValue:body forKey:@"body"];//商品描述
    [originOrderdic setValue:out_trade_no forKey:@"out_trade_no"];//订单号
    [originOrderdic setValue:total_fee forKey:@"total_fee"];//金额,注意100=1元
    [originOrderdic setValue:spbill_create_ip forKey:@"spbill_create_ip"];//终端IP
    [originOrderdic setValue:notify_url forKey:@"notify_url"];//通知地址
    [originOrderdic setValue:trade_type forKey:@"trade_type"];//交易类型
    [originOrderdic setValue:time_start forKey:@"time_start"];
    // 获取签名
    NSString *sign =[WXSignUtil createMd5Sign:originOrderdic];
    [originOrderdic setValue:sign forKey:@"sign"];//签名
    
    NSLog(@"统一下单参数 ===== %@",originOrderdic);
    // 转换成xml
    NSString *xmlString = [originOrderdic XMLString];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //这里传入的xml字符串只是形似xml，但是不是正确是xml格式，需要使用af方法进行转义
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    [manager.requestSerializer setValue:@"text/xml;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"https://api.mch.weixin.qq.com/pay/unifiedorder" forHTTPHeaderField:@"SOAPAction"];
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
        return xmlString;
    }];
    //发起请求
    [manager POST:@"https://api.mch.weixin.qq.com/pay/unifiedorder"
       parameters:xmlString
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
              // LXLog(@"responseString is %@",responseString);
              //将微信返回的xml数据解析转义成字典
              NSDictionary *dic = [NSDictionary dictionaryWithXMLString:responseString];
              NSLog(@"++++++++++%@,%@",dic,[dic objectForKey:@"return_msg"]);
              //此处为调起支付接口
              NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:dic];
              mutableDic[@"timeStamp"] = time_start;
              [self sendWechatPayQueryOrderParameters:mutableDic];
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              
          }];
}
/** 调起微信支付 */
+ (void)sendWechatPayQueryOrderParameters:(NSDictionary *)orderParameters {
    /***生成签名信息 */
    NSString *appid = kWxAPPID;
    NSString *nonceStr = [orderParameters objectForKey:@"nonce_str"];
    NSString *package = @"Sign=WXPay";
    NSString *partnerId = [orderParameters objectForKey:@"mch_id"];
    NSString *prepayId = [orderParameters objectForKey:@"prepay_id"];
    NSString *timeStamp = [orderParameters objectForKey:@"timeStamp"];
    
    NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
    signParams[@"appid"] = appid;
    signParams[@"partnerid"] = partnerId;
    signParams[@"prepayid"] = prepayId;
    signParams[@"package"] = package;
    signParams[@"noncestr"] = nonceStr;
    signParams[@"timestamp"] = timeStamp;
    NSString *sign = [WXSignUtil createMd5Sign:signParams];
    
    PayReq *request = [[PayReq alloc] init];
    
    request.openID = appid;
    
    request.partnerId = partnerId;
    
    request.prepayId= prepayId;
    
    request.package = package;
    
    request.nonceStr= nonceStr;
    
    request.timeStamp= [timeStamp integerValue];
    
    request.sign = sign;
    
    [WXApi sendReq:request];
}

@end
